package ru.ifmo.common.xml;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author avhaliullin
 */
public class XmlUtil {
    public static Iterable getNodeListIterable(final NodeList nodeList) {
        return new Iterable() {
            public Iterator iterator() {
                return new Iterator() {
                    int index = 0;

                    public boolean hasNext() {
                        return index < nodeList.getLength();
                    }

                    public Object next() {
                        if (hasNext()){
                            return nodeList.item(index++);
                        } else {
                            throw new NoSuchElementException();
                        }
                    }

                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }

    public static Element getSingleElement(Element parent, String name) {
        for (Object o : getNodeListIterable(parent.getElementsByTagName(name))) {
            if (o instanceof Element) {
                return (Element) o;
            }
        }
        return null;
    }
}
